const { getArtifacts, categories } = require('../../utils/data');

Page({
  data: {
    categories: ['所有', ...categories.slice(1)], // 分类
    selectedCategoryIndex: 0, // 当前分类
    items: [], // 当前页数据
    currentPage: 1, // 当前页码
    pageSize: 8, // 每页文物数量
    totalPages: 1, // 总页数
    searchQuery: '', // 搜索关键字
    loading: false, // 是否加载中,
    pages: [] // 页码显示数组
  },

  onLoad() {
    this.loadItems();
  },

  loadItems() {
    const { currentPage, pageSize, categories, selectedCategoryIndex, searchQuery } = this.data;
    const category = categories[selectedCategoryIndex];
    this.setData({ loading: true });
    const { data, total } = getArtifacts({
      page: currentPage,
      pageSize,
      category,
      query: searchQuery,
    });

    this.setData({
      items: data,
      totalPages: Math.ceil(total / pageSize),
      loading: false
    });

    this.generatePageNumbers();  // 更新分页按钮
  },

  generatePageNumbers() {
    const { currentPage, totalPages } = this.data;
    const pages = [];

    if (totalPages <= 5) {
      // 总页数少于或等于5时，显示全部页码
      for (let i = 1; i <= totalPages; i++) pages.push(i);
    } else {
      // 当前页码靠近开头
      if (currentPage <= 3) {
        pages.push(1, 2, 3, 4, '...', totalPages);
      }
      // 当前页码靠近末尾
      else if (currentPage >= totalPages - 2) {
        pages.push(1, '...', totalPages - 3, totalPages - 2, totalPages - 1, totalPages);
      }
      // 当前页码居中
      else {
        pages.push(1, '...', currentPage - 1, currentPage, currentPage + 1, '...', totalPages);
      }
    }

    this.setData({ pages });
  },

  onCategoryChange(e) {
    this.setData({
      selectedCategoryIndex: e.detail.value,
      currentPage: 1,
    });
    this.loadItems();
  },

  onSearchInput(e) {
    this.setData({
      searchQuery: e.detail.value,
      currentPage: 1,
    });
    this.loadItems();
  },

  prevPage() {
    if (this.data.currentPage > 1) {
      this.setData({ currentPage: this.data.currentPage - 1 });
      this.loadItems();
    }
  },

  nextPage() {
    if (this.data.currentPage < this.data.totalPages) {
      this.setData({ currentPage: this.data.currentPage + 1 });
      this.loadItems();
    }
  },

  goToPage(e) {
    const page = e.currentTarget.dataset.page;
    if (page !== this.data.currentPage) {
      this.setData({ currentPage: page });
      this.loadItems();
    }
  },
  //下拉刷新
  onPullDownRefresh: async function () {
    console.log("开始下拉刷新");
    await this.loadItems();
    wx.stopPullDownRefresh(); // 停止下拉刷新动画
    wx.showToast({
      title: '刷新完成',
      icon: 'success',
      duration: 2000
    });
  }
});
